package com.auth.config.filter.client;

import com.auth.config.exception.ConfigException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.OAuth2Request;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author: hw
 * @date: 2021/11/26 14:46
 */
public class ClientDetailsServiceAuth {


    @Autowired
    private ClientDetailsService clientDetailsService;

    public OAuth2Request createOAuth2Request(String appId,String redirectUrl){
        ClientDetails clientDetails = null;
        try {
            clientDetails = clientDetailsService.loadClientByClientId(appId);
        }catch (NoSuchClientException e){
            throw new ConfigException("app_Id error");
        }
        Set<String> registeredRedirectUri = clientDetails.getRegisteredRedirectUri();
        if (!registeredRedirectUri.contains(redirectUrl)){
            throw  new ConfigException("redirect_URI  Undefined");
        }
        Map<String,String> map = new HashMap<>();
        map.put("app_Id",appId);
        map.put("redirect_URI",redirectUrl);
        return new OAuth2Request(map,clientDetails.getClientId(),clientDetails.getAuthorities(),true,clientDetails.getScope(),
                clientDetails.getResourceIds(),redirectUrl,clientDetails.getAuthorizedGrantTypes(),null);
    }
}
